/*
 * Copyright (c) 2008 by 1eEurope (Switzerland) AG, Thalwil
 *
 * Customer:	1eEurope (Switzerland) AG
 * Project:		BKS
 * Created:		30.09.2008, WBL
 *
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Collections.Specialized;
using System.Xml;
using System.IO;
using System.Xml.Xsl;
using System.Web.UI.WebControls;
using By1eEurope.BKS.Tools.Utils;

namespace By1eEurope.BKS.Controls
{
    /// <summary>
    /// Provides a part of the value of a field of the current page in the ValuePart Property
    /// </summary>
    public class FieldValueReader : WebControl
    {
        private string delimiter;
        /// <summary>
        /// string to split the field value
        /// </summary>
        public string Delimiter
        {
            set { this.delimiter = value; }
        }

        private int partIndex;
        /// <summary>
        /// index of the value part after splitting with the indicated delimiter
        /// </summary>
        public int PartIndex
        {
            set { this.partIndex = value; }
        }

        private string fieldName;
        /// <summary>
        /// name of the field whose content is provided
        /// </summary>
        public string FieldName
        {
            set { this.fieldName = value; }
        }

        private bool debug = false;
        /// <summary>
        /// if true, the ValuePart Property is rendered
        /// </summary>
        public bool Debug
        {
            set { this.debug = value; }
        }

        private string valuePart = null;
        /// <summary>
        /// Provides the value
        /// </summary>
        public string ValuePart
        {
            get
            {
                try
                {
                    if (string.IsNullOrEmpty(this.valuePart))
                    {
                        string s = SPContext.Current.ListItem[this.fieldName] as string;

                        if (s != null)
                        {
                            string[] parts = s.Split(new string[] { this.delimiter }, StringSplitOptions.RemoveEmptyEntries);
                            this.valuePart = parts[this.partIndex];
                        }
                    }
                }
                catch {}
                return this.valuePart;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            if (debug)
                writer.Write(this.ValuePart);
        }


    }
}
